﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI;
using DataAccess.Models;
using DataAccess.Repository;

namespace KPI
{
	public partial class WriteMail : BasePage
	{
		private MailMessage _TheMailMessage;
		private IMailRepository _MailRepository;
		private IUserRepository _UserRepository;

		public int TheMailID
		{
			get
			{
				return CommonHelper.QueryStringInt("mailid");
			}
		}

		public MailMessage TheMailMessage
		{
			get
			{
				if(_TheMailMessage == null)
				{
					if(TheMailID > 0)
					{
						if(_MailRepository == null)
						{
							_MailRepository = new MailRepository();
						}

						_TheMailMessage = _MailRepository.GetTheMailMessage(TheMailID);
					}
					else
					{
						_TheMailMessage = new MailMessage();
					}
				}

				return _TheMailMessage;
			}
		}

		/// <summary>
		/// 邮件附件文件夹物理路径
		/// </summary>
		public string MailAttPhysicalPath
		{
			get
			{
				var result = Server.MapPath("mailattfile") + "/" + DateTime.Now.ToString("yyyyMM");

				if(!Directory.Exists(result))
				{
					Directory.CreateDirectory(result);
				}

				return result;
			}
		}

		public string MailAttFolder
		{
			get
			{
				var result = "mailattfile" + "/" + DateTime.Now.ToString("yyyyMM");

				var f = Server.MapPath(result);

				if(!Directory.Exists(f))
				{
					Directory.CreateDirectory(f);
				}

				return result;
			}
		}

		protected void Page_Init(object sender, EventArgs e)
		{
			if(TheCurrentLoginUser == null)
			{
				Response.Redirect("~/Login.aspx");
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				new CKFinder.FileBrowser
				{
					BasePath = "/ckfinder/",
					DisableThumbnailSelection = true
				}.SetupCKEditor(this.CKEditorMailContent);

				BindMailMessage();
			}
		}

		protected void btnSend_Click(object sender, EventArgs e)
		{
			if(Page.IsValid)
			{
				var fileName = ProcessAttFile();

				var mailMessage = new MailMessage();

				if(!string.IsNullOrWhiteSpace(fileName))
				{
					mailMessage.MailAttFile = fileName;
				}

				mailMessage.MailContent = CKEditorMailContent.Text;
				mailMessage.MailSendTime = DateTime.Now;
				mailMessage.MailFrom = TheCurrentLoginUser.UserName;
				mailMessage.MailIsDelete = 0;
				mailMessage.MailSubject = txtMailSubject.Text.Trim();

				GetMailRecievers(mailMessage);

				if(_MailRepository == null)
				{
					_MailRepository = new MailRepository();
				}

				if(_MailRepository.CreateMail(mailMessage))
				{
					Response.Redirect("~/MailOutbox.aspx");
				}
				else
				{
					ShowMessage("出错了, 请稍后再试或联系相关技术人员.", true);
				}
			}
		}

		protected void btnCancel_Click(object sender, EventArgs e)
		{
			Response.Redirect("~/MailInbox.aspx");
		}

		protected void Page_UnLoad(object sender, EventArgs e)
		{
			if(CKEditorMailContent != null)
			{
				CKEditorMailContent.Dispose();
			}

			if(_MailRepository != null)
			{
				((IDisposable)_MailRepository).Dispose();
			}
			if(_UserRepository != null)
			{
				((IDisposable)_UserRepository).Dispose();
			}
		}

		private void GetMailRecievers(MailMessage theMailMessage)
		{
			if(!string.IsNullOrWhiteSpace(hfMailRecievers.Value) && theMailMessage != null)
			{
				var arrDepts = hfMailRecievers.Value.Trim().Split(' ');

				if(arrDepts != null && arrDepts.Length > 0)
				{
					var currentUsersDept = TheCurrentLoginUser.DeptID;
					var lstDepts = new List<int>();

					foreach(var item in arrDepts)
					{
						var theDeptID = 0;
						if(int.TryParse(item, out theDeptID))
						{
							if(currentUsersDept.Equals(theDeptID))
							{
								continue;
							}

							lstDepts.Add(theDeptID);
						}
						else
						{
							if(theMailMessage.ListMailReciever == null)
							{
								theMailMessage.ListMailReciever = new List<MailReciever>();
							}

							theMailMessage.ListMailReciever.Add(new MailReciever()
							{
								Reciever = item
							});
						}
					}

					if(_UserRepository == null)
					{
						_UserRepository = new UserRepository();
					}

					var lstUnitAdmins = _UserRepository.GetDocRecieversByGroups(lstDepts);

					if(lstUnitAdmins != null && lstUnitAdmins.Count > 0)
					{
						if(theMailMessage.ListMailReciever == null)
						{
							theMailMessage.ListMailReciever = new List<MailReciever>();
						}

						foreach(var item in lstUnitAdmins)
						{
							theMailMessage.ListMailReciever.Add(new MailReciever()
							{
								Reciever = item.UserName
							});
						}
					}
				}
			}
		}

		private string ProcessAttFile()
		{
			var result = string.Empty;

			if(fuMailAtt.FileBytes != null && fuMailAtt.FileBytes.Length > 0)
			{
				if(fuMailAtt.FileBytes.Length > 0 && fuMailAtt.FileBytes.Length <= 1024 * 1024 * 10)
				{
					try
					{
						var theFileRealName = GetFileRealName(fuMailAtt.FileName);
						result = this.MailAttFolder + "/" + theFileRealName;

						fuMailAtt.SaveAs(this.MailAttPhysicalPath + "/" + theFileRealName);
					}
					catch(Exception exc)
					{
						ShowMessage(exc.Message, true);
					}
				}
			}

			return result;
		}

		private string GetFileRealName(string fileName)
		{
			var result = string.Empty;

			if(!string.IsNullOrWhiteSpace(fileName))
			{
				var fn = Path.GetFileName(fileName);
				result = fn.Split('.')[0] + "_" + Guid.NewGuid().ToString() + "." + fn.Split('.')[1];
			}

			return result;
		}

		private void BindMailMessage()
		{
			if(TheMailMessage != null && TheMailMessage.MailID > 0)
			{
				hfMailRecievers.Value = TheMailMessage.MailFrom;
				var cname = string.Empty;
				var name = TheMailMessage.MailFrom;

				using(var userRepository = new UserRepository())
				{
					DataAccess.Models.User2 theUser2 = userRepository.GetUser2(TheMailMessage.MailFrom);

					if(theUser2 == null)
					{
						var theUser = userRepository.GetUser(TheMailMessage.MailFrom);

						if(theUser != null)
						{
							cname = theUser.UserName;
						}
					}
					else
					{
						cname = theUser2.UserCName;
					}
				}

				writemail_recievercontainer_recievers.InnerHtml = "<div class='selectedgroupcontainer' onclick='selectedgroupcontainer_click(this);' title='点击移除'>" +
											 "<span class='selectedgroup'>" + cname + "</span>" +
											 "<input type='hidden' id='user" + name + "' value='" + name + "'></input>" +
										"</div>";

				txtMailSubject.Text = "回复: " + TheMailMessage.MailSubject;
				CKEditorMailContent.Text = "<br /><br /><hr />" + TheMailMessage.MailContent;
			}
		}
	}
}